package com.itianyu.blog.dao.implementations;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.itianyu.blog.dao.beans.RelUserRole;
import com.itianyu.blog.dao.beans.User;
import com.itianyu.blog.dao.interfaces.UserInterface;

/**
 * 管理用户实现类
 * @author wumgji
 */
@Service
public class UserImplementation implements UserInterface {

	private static final long serialVersionUID = 1L;

	@PersistenceContext
	private EntityManager em;

	// 创建用户实体
	public User createUser() {
		User usuario = new User();
		return usuario;
	}

	// 保存用户信息
	@Transactional
	public void saveUser(User user) {
		em.merge(user);
		
		RelUserRole relUserRole=new RelUserRole();
		relUserRole.setRole("ROLE_USER");
		relUserRole.setUserName(user.getUsername());
		em.merge(relUserRole);
		return;
	}

	// 根据用户ID删除用户信息
	@Transactional
	public void deleteUser(String id) {
		User user = em.find(User.class, id);
		if (user != null) {
			em.remove(user);
		}
		return;
	}

    	// 根据用户ID查询用户信息
	 public User findUserByName(String username) {
		return em.find(User.class, username);
	}
	
	// 根据用户名称 查询用户信息
		public User findUser(String id) {
			return em.find(User.class, id);
		}

	// 查询用户列表
	@Transactional(readOnly = true)
	@SuppressWarnings("unchecked")
	public List<User> findUserEntities() {
		Query q = em.createQuery("SELECT object(o) FROM User as o ORDER BY o.creationDate desc");
		List<User> items = q.getResultList();
		return items;
	}

	// 计算用户列表的总数
	@Transactional(readOnly = true)
	@SuppressWarnings("unchecked")
	public int getUserCount() {
		Query q = em.createQuery("SELECT object(o) FROM User as o");
		List<User> items = q.getResultList();
		return items.size();
	}

}
